//
//  PlayRadioTableViewController.m
//  news
//
//  Created by lanou on 15/12/17.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "PlayRadioTableViewController.h"
#import "PlayRadioView.h"
#import "PlayRadioTableViewCell.h"
#import "PlayRadioModel.h"
#import "RadioPlay.h"
#import "MJRefresh.h"

@interface PlayRadioTableViewController ()<RadioPlayDelegate>

@property (nonatomic, retain)PlayRadioTableViewCell *cell;

@property (nonatomic, retain)PlayRadioView *playRadioV;

@property (nonatomic, retain)NSTimer *timer;

@property (nonatomic, retain)AVPlayerItem *playerItem;



@end

@implementation PlayRadioTableViewController
{
    NSInteger indexForRow;
}
static int index1 = 0;

- (NSMutableArray *)allArray {
    if (!_allArray) {
        _allArray = [[NSMutableArray alloc] init];
    }
    return _allArray;
}

- (void)reloadDataWithModel {

    [self.playRadioV.pictureView setImageWithURL:[NSURL URLWithString:[RadioPlay sharedRadioPlay].playRadioModel.imgsrc] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
    
    self.playRadioV.titleLabel.text = [RadioPlay sharedRadioPlay].playRadioModel.title;
    
    indexForRow = [RadioPlay sharedRadioPlay].item;
    [self.tableView reloadData];
   
}


- (void)startToPlay {
    
    [[RadioPlay sharedRadioPlay] startPlaySong];
    if ([RadioPlay sharedRadioPlay].readyToPlay == YES) {
        [self.playRadioV.playBtn setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
    }
}



- (void)ReFreshData {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:kDetailRadio2,self.tid,[self.allArray count],[self.allArray count] + 20]];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    for (NSDictionary *dic in rootDic[self.tid]) {
        PlayRadioModel *playRadioModel = [[PlayRadioModel alloc] init];
        [playRadioModel setValuesForKeysWithDictionary:dic];
        [self.allArray addObject:playRadioModel];
    }
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.playRadioV = [[PlayRadioView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 330)];
    [self.playRadioV.backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.playRadioV;
    self.playRadioV.playBtn.tag = 1000;
    [self.playRadioV.playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playRadioV.nextBtn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    [self.playRadioV.prevBtn addTarget:self action:@selector(prev) forControlEvents:UIControlEventTouchUpInside];
 
    
    
    [self.tableView registerClass:[PlayRadioTableViewCell class] forCellReuseIdentifier:@"cell1"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithModel) name:@"loadData" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startToPlay) name:@"readyToPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextRadioPaly) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    [RadioPlay sharedRadioPlay].playRadioTVC = self;
    [RadioPlay sharedRadioPlay].radioPlayerDelegate = self;
    
    [[RadioPlay sharedRadioPlay] loadRadioInfo1];
    
    // 上拉刷新
    __weak PlayRadioTableViewController *playRadioTVB = self;
    [self.tableView addFooterWithCallback:^{
//        NSLog(@"上拉刷新");
        [playRadioTVB ReFreshData];
        
        [playRadioTVB.tableView footerEndRefreshing];
    }];
    
    // 下拉关闭本页面
    [self.tableView  addHeaderWithCallback:^{
        [playRadioTVB back];
        [playRadioTVB.tableView headerEndRefreshing];
    }];
    playRadioTVB.tableView.headerPullToRefreshText = @"下拉可以关闭本页面";
    playRadioTVB.tableView.headerRefreshingText=@"正在关闭本页面";
    playRadioTVB.tableView.headerReleaseToRefreshText=@"松开立即关闭本页面";
    


    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



// 设置cell中字体的颜色
- (void)setCellColorForTextWithRow:(NSInteger)row color:(UIColor *)color{
    
    NSString *str = self.cell.titleLabel.text;
    NSRange range = NSMakeRange(0, str.length);
    NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:str];
    [str1 addAttribute:NSForegroundColorAttributeName value:color range:range];
    self.cell.titleLabel.attributedText = str1;
}


- (void)back {
//    [RadioPlay sharedRadioPlay].radioPlayerDelegate = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 播放
- (void)playAction:(UIButton *)button {
    // 通过tag值改变播放、暂停图片
    self.playRadioV.playBtn.tag += 1;
    int buttonTag = (self.playRadioV.playBtn.tag - 1000) % 2;
    if (buttonTag == 1) {
        [self.playRadioV.playBtn setImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
        [self.timer invalidate];
        [[RadioPlay sharedRadioPlay] stopPlaySong];
    } else {
        [self.playRadioV.playBtn setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
        [RadioPlay sharedRadioPlay].readyToPlay = YES;
        [[RadioPlay sharedRadioPlay] startPlaySong];
    }
}

// 下一个
- (void)next {
    [[RadioPlay sharedRadioPlay] nextRadio];
    PlayRadioModel *playRadioModel = self.allArray[[RadioPlay sharedRadioPlay].item];
    [self.playRadioV.pictureView setImageWithURL:[NSURL URLWithString:playRadioModel.imgsrc]];
    index1 += 1;
    
    [self setCellColorForTextWithRow:indexForRow color:[UIColor blackColor]];
}



// 上一个
- (void)prev {
    [[RadioPlay sharedRadioPlay] prevRadio];
    PlayRadioModel *playRadioModel = self.allArray[[RadioPlay sharedRadioPlay].item];
    [self.playRadioV.pictureView setImageWithURL:[NSURL URLWithString:playRadioModel.imgsrc]];
    index1 -= 1;
    [self.tableView reloadData];
    [self setCellColorForTextWithRow:indexForRow color:[UIColor blackColor]];
}


// 当一个播放结束的时候，自动播放下一个
- (void)nextRadioPaly {
    [[RadioPlay sharedRadioPlay] nextRadio];
    PlayRadioModel *playRadioModel = self.allArray[[RadioPlay sharedRadioPlay].item];
    [self.playRadioV.pictureView setImageWithURL:[NSURL URLWithString:playRadioModel.imgsrc]];
    [self setCellColorForTextWithRow:indexForRow color:[UIColor blackColor]];
}



// 代理方法
- (void)audioManagerRadioProgress:(float)grogress {
    if ([RadioPlay sharedRadioPlay].readyToPlay == YES) {
        self.playRadioV.pictureView.transform = CGAffineTransformRotate(self.playRadioV.pictureView.transform, 0.01);
    } else {  }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return [self.allArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

#pragma mark-
#pragma mark ------ 加载单元格 ------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
    
    self.cell.playRadioModel = self.allArray[indexPath.row];
    
    if (indexPath.row == index1) {
        // 获取cell中的字符串，改变字符串的颜色
        NSString *str = self.cell.titleLabel.text;
        NSRange range = NSMakeRange(0, str.length);
        NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:str];
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        self.cell.titleLabel.attributedText = str1;
    }
    
    return self.cell;
}

#pragma mark-
#pragma mark ------ 单元格点击事件 ------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayRadioModel *playRadioModel = self.allArray[indexPath.row];
    [RadioPlay sharedRadioPlay].radioListArray = self.allArray;
    [RadioPlay sharedRadioPlay].item = [indexPath row];
    [self.playRadioV.pictureView setImageWithURL:[NSURL URLWithString:playRadioModel.imgsrc] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
    [[RadioPlay sharedRadioPlay] loadRadioInfo1];
    index1 = (int)[indexPath row];
    [self setCellColorForTextWithRow:indexForRow color:[UIColor blackColor]];
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
